package com.example.springboot;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.ha.CatalinaCluster;
import org.apache.catalina.ha.ClusterMessageBase;
import org.apache.catalina.ha.ClusterValve;
import org.apache.catalina.valves.ValveBase;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import java.io.IOException;

@Component
public class MyMapValue extends ValveBase implements ClusterValve, ApplicationListener<KeyValueChangeEvent> {
    private CatalinaCluster cluster;

    @Override
    public CatalinaCluster getCluster() {
        return cluster;
    }

    @Override
    public void setCluster(CatalinaCluster cluster) {
        this.cluster=cluster;
    }

    @Override
    public void invoke(Request request, Response response) throws ServletException, IOException {
        getNext().invoke(request, response);
    }


    @Override
    public void onApplicationEvent(KeyValueChangeEvent event) {
        String key = event.getKey();
        String value = event.getValue();
        cluster.send(new MyKeyValueClusterMessage(key, value));
    }

    public static class MyKeyValueClusterMessage extends ClusterMessageBase {
        private final String key;
        private final String value;

        public MyKeyValueClusterMessage(String key, String value) {
            this.key=key;
            this.value=value;
        }

        @Override
        public String getUniqueId() {
            return System.currentTimeMillis()+key;
        }

        public String getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }
    }
}
